package org.jeecg.modules.engine.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.engine.entity.Engineering;
import org.jeecg.modules.engine.entity.Requirement;
import org.jeecg.modules.engine.mapper.EngineeringMapper;
import org.jeecg.modules.engine.mapper.RequirementMapper;
import org.jeecg.modules.engine.service.IRequirementService;
import org.jeecg.modules.sync.service.ISyncService;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @Description: 需求表
 * @Author: jeecg-boot
 * @Date:   2020-07-20
 * @Version: V1.0
 */
@Service
public class RequirementServiceImpl extends ServiceImpl<RequirementMapper, Requirement> implements IRequirementService {

	@Autowired
	private RequirementMapper requirementMapper;

	@Autowired
	private EngineeringMapper engineeringMapper;

	@Autowired
	private ISyncService syncService;

	@Override
	public List<Requirement> selectByMainId(String mainId) {
		return requirementMapper.selectByMainId(mainId);
	}

	@Override
	public Integer saveRequirement(Requirement requirement) {
		SimpleDateFormat format =new SimpleDateFormat("yyyy-MM-dd");
		String currentDate = format.format(new Date());
		Requirement req = null;
		List<Requirement> requirements = baseMapper.selectList(new LambdaQueryWrapper<Requirement>().gt(Requirement::getCreateTime, currentDate + " 00:00:00").lt(Requirement::getCreateTime, currentDate + " 23:59:59").orderByDesc(Requirement::getCreateTime));
		if (requirements!=null && requirements.size()>0){
			req = requirements.stream().findFirst().get();
		}
//		Integer count = baseMapper.selectCount(new LambdaQueryWrapper<Requirement>().gt(Requirement::getCreateTime, currentDate + " 00:00:00").lt(Requirement::getCreateTime, currentDate + " 23:59:59"));
//		format= new SimpleDateFormat("yyMMdd");
//		currentDate = format.format(new Date());
//		requirement.setRequirementNo(currentDate+String.format("%03d",(count+1)));

		int sort = 0;
		if (req != null && req.getSort() != null){
			sort = req.getSort();
		}
		requirement.setSort(sort+1);
		int insertCount = baseMapper.insert(requirement);
		return insertCount;
	}

	@Override
	public Integer updateRequirment(Requirement requirement) {
		if (requirement.getRequirementNo()!=null && !requirement.getRequirementNo().equals("")){
			Integer status = syncERP(requirement, 1);
			if (status == 1){
				throw new RuntimeException("已转采购单，不允许编辑");
			}
			status = syncERP(requirement, 0);
			if (status != 0){
				throw new RuntimeException("编辑失败");
			}
		}
		return baseMapper.updateById(requirement);
	}

	@Override
	public Integer deleteRequirmentById(String id) {
		Requirement requirement = baseMapper.selectOne(new LambdaQueryWrapper<Requirement>().eq(Requirement::getId, id));
		if (requirement.getRequirementNo()!=null && !requirement.getRequirementNo().equals("")){
			Integer status = syncERP(requirement, 1);
			if (status == 1){
				throw new RuntimeException("已转采购单，不允许删除");
			}
		}
		return baseMapper.deleteById(id);
	}

	@Override
	public Result deleteBatchRequirement(List<String> idList) {
		List<Requirement> requirementList = baseMapper.selectBatchIds(idList);
		AtomicInteger successCount = new AtomicInteger(0);
		AtomicInteger failCount = new AtomicInteger(0);
		requirementList.forEach(p ->{
			if (p.getRequirementNo()!=null && !p.getRequirementNo().equals("")){
				Integer status = syncERP(p, 1);
				if (status == 1){
					failCount.set(failCount.get() + 1);
				}else {
					if (baseMapper.deleteById(p.getId()) == 1){
						successCount.set(successCount.get()+1);
					}
				}
			}else {
				if (baseMapper.deleteById(p.getId()) == 1){
					successCount.set(successCount.get()+1);
				}
			}
		});
		if (successCount.get() == requirementList.size()){
			return Result.ok("操作成功，批量删除成功");
		}else if (successCount.get()!=0 && successCount.get() < requirementList.size()){
			return Result.ok("操作成功，部分已转采购单，未删除");
		}
		throw new RuntimeException("操作失败，全部已转采购单，未删除");
	}

	@Override
	public Integer generateRequisitions(String mainId) {
		List<Requirement> requirements = baseMapper.selectList(new LambdaQueryWrapper<Requirement>().eq(Requirement::getEngineeringId, mainId));
		if (requirements == null || requirements.size()==0){
			throw new RuntimeException("请先添加一条物料需求，再做同步");
		}
		if (requirements.stream().filter(p -> p.getRequirementNo() ==null || p.getRequirementNo().equals("")).count() == 0){
			throw new RuntimeException("该列表的数据已经全部生成过请购单到erp了，无需再次同步");
		}
		List<Requirement> requirementStream = requirements.stream().filter(p -> p.getRequirementNo() != null).collect(Collectors.toList());
		String requirementNo = "";
		if (requirementStream.size()>0){
			requirementNo = requirementStream.stream().findFirst().get().getRequirementNo();
		}else {
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			String currentDay = format.format(new Date());
			Integer index = baseMapper.getRequirementNoIndex(currentDay);
			format= new SimpleDateFormat("yyMMdd");
			currentDay = format.format(new Date());
			requirementNo = currentDay+String.format("%03d",(index == null ? 1:index+1));
		}
		//还未生成采购单的集合
		List<Requirement> requirementCollect = requirements.stream().filter(p -> p.getRequirementNo() == null || p.getRequirementNo().equals("")).collect(Collectors.toList());
		String finalRequirementNo = requirementNo;
		requirementCollect.forEach(requirement -> {
			requirement.setRequirementNo(finalRequirementNo);
			Requirement updateRequirement = new Requirement();
			updateRequirement.setId(requirement.getId());
			updateRequirement.setRequirementNo(finalRequirementNo);

			syncERP(requirement,0);

			baseMapper.updateById(updateRequirement);
		});
		return 0;
	}


	public Integer syncERP(Requirement requirement,int opea){

		Map<String,Object> map = new HashMap<>();
		map.put("NO",requirement.getRequirementNo());
		map.put("SQ_DD",new java.sql.Date(System.currentTimeMillis()));
		map.put("ITM",requirement.getSort());
		map.put("PRD_NO",requirement.getMatCode());
		// 获取登录用户信息
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		map.put("USR",sysUser.getUsername());
		map.put("BAT_NO",null);
		map.put("QTY",requirement.getCount());
		map.put("WH","0000");
		map.put("DEP",requirement.getSysOrgCode());
		map.put("BIL_TYPE",null);
		Engineering engineering = engineeringMapper.selectOne(new LambdaQueryWrapper<Engineering>().eq(Engineering::getId, requirement.getEngineeringId()));
		map.put("CAS_NO",engineering.getEngineCode());
		map.put("FLAG",opea);
		Integer integer = syncService.sp_mes_sq(map);
		return integer;
	}


//	public Integer syncERP(Requirement requirement,int opea){
//		Connection conn = null;
//		try{
//			conn = DriverManager.getConnection("jdbc:sqlserver://116.63.163.10:2196;DatabaseName=DB_XS;", "sa", "txinkj@123");
//			String call = "{ call SP_MES_SQ(?,?,?,?,?,?,?,?,?,?,?,?) }";
//			CallableStatement callableStatement = conn.prepareCall(call);
//			callableStatement.setString(1,requirement.getRequirementNo());
//			callableStatement.setDate(2,new java.sql.Date(System.currentTimeMillis()));
//			callableStatement.setInt(3,requirement.getSort());
//			callableStatement.setString(4,requirement.getMatCode());
//			// 获取登录用户信息
//			LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//			callableStatement.setString(5,sysUser.getUsername());
//			callableStatement.setString(6,null);
//			callableStatement.setInt(7,requirement.getCount());
//			callableStatement.setString(8,"0000");
//			callableStatement.setString(9,requirement.getSysOrgCode());
//			callableStatement.setString(10,null);
//			Engineering engineering = engineeringMapper.selectOne(new LambdaQueryWrapper<Engineering>().eq(Engineering::getId, requirement.getEngineeringId()));
//			callableStatement.setString(11,engineering.getEngineCode());
//			callableStatement.setInt(12,opea); //插入操作
////			ResultSet resultSet = callableStatement.executeQuery();
//////			int anInt = resultSet.getInt(1);
//////			System.out.println(anInt);
//////			return anInt;
//			callableStatement.execute();
//			return 0;
//		}catch (Exception e){e.printStackTrace();}finally {
//			if (conn != null){
//				try {
//					conn.close();
//				} catch (SQLException e) {
//					e.printStackTrace();
//				}
//			}
//		}
//		return 1;
//	}
}
